<template>
    <fieldset>
        <legend>三级联动</legend>
        省:
        <select v-model="sel1" @change="provienceChange(sel1)">
            <option v-for="item in provience" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>
        市:
        <select v-model="sel2" @change="cityChange(sel2)">
            <option v-for="item in city" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>
        区:
        <select v-model="sel3">
            <option v-for="item in area" :key="item.id" :value="item.id">{{item.name}}</option>
        </select>
    </fieldset>
</template>


<script>
import * as api from "@/api/select"

export default{
    data(){
        return {
            // 省的数据
            provience:[],
            // 选中省的id
            sel1:1,
            // 市的数据
            city:[],
            // 选中市的id
            sel2:1,
            // 区的数据
            area:[],
            // 选中区的id
            sel3:1
        }
    },
    mounted(){
        api.fetchData()
            .then(res => {
                console.log(res);
                this.provience = res
                // 获取默认第一条的id
                let pid = res[0].id;
                this.provienceChange(pid)

            })
    },
    methods:{
        provienceChange(pid){
            // 当省变化的时候，获取选中的省的id，发起请求，请求市的数据
            api.fetchCity(pid)
                .then(res => {
                    this.city = res

                    if(res.length>0)

                    this.sel2 = res[0].id
                    
                    
                    let pid1 = res[0].id
                    this.cityChange(pid1)
                })
        },
        cityChange(pid1){
            api.fetchArea(pid1)
                .then(res => {
                    this.area = res
                    // console.log(res)
                    if(res.length >0){
                        this.sel3 = res[0].id
                    }
                })
        }
    }
}



</script>
<style scoped>

    select{
        width: 100px;
    }
</style>